<?php

namespace ua_backend\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use ua_backend\models\User;

/**
 * UserSearch represents the model behind the search form about `ua_backend\models\User`.
 */
class UserSearch extends User
{
    /**
     * @inheritdoc
     */
    public $skey;

    public function scenarios()
    {
        return Model::scenarios();
    }


    public function search($params)
    {
        $query = User::find()->from('user u')->where(['not',['u.openid'=>null]]);
        $query->andWhere(['not',['u.nickname'=>null]]);
        $query->orderBy('u.id desc');

        if(isset(Yii::$app->request->get('UserSearch')['skey'])){
            $skey = Yii::$app->request->get('UserSearch')['skey'];
            $query->andFilterWhere(['like', 'u.nickname',  urlencode($skey)]);
            $query->orFilterWhere(['like', 'u.nickname',  json_encode($skey)]);
            $query->orFilterWhere(['u.id'=>$skey]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pagesize' => Yii::$app->params['pageSize'],
            ],
        ]);

        return $dataProvider;
    }


    public function download($params)
    {
        $query = User::find()->from('user u')->where(['not',['u.openid'=>null]]);
        $query->andWhere(['not',['u.nickname'=>null]]);
        $query->andWhere(['>','u.id',1]);
        $this->load($params);

        $aid = Yii::$app->user->getId();
        $role = Yii::$app->authManager->getRolesByUser($aid);
        if(isset($role['后台普通'])){
            $query->leftJoin('rel_user_dealer r','r.uid=u.id');
            $query->andWhere(['r.did'=>$aid]);
        }
        $query->orderBy('u.id desc');

        $start = Yii::$app->request->get('UserSearch')['date_start'];
        $end = Yii::$app->request->get('UserSearch')['date_end'];
        $range = [
            'and',
            ['>=', 'u.created_date', $start],
            ['<=', 'u.created_date', $end],
        ];
        $query->andWhere($range);

        $dataProvider = new ActiveDataProvider([
            'query' => $query
        ]);

        return $dataProvider;
    }
}
